<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-select style="width:140px" v-model="find_data.routeSimpleName" placeholder="请选择行程简称" clearable>
                        <el-option v-for="item in routeSimpleName_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-select style="width:120px;margin-left: 10px;" v-model="find_data.serviceMan" placeholder="请选业务员"
                        clearable>
                        <el-option v-for="item in getServiceMans_list" :key="item.ftUserId" :label="item.realName"
                            :value="item.ftUserId" />
                    </el-select>

                    <el-select style="width:100px;margin-left: 10px;" v-model="find_data.timeType"
                        :placeholder="'时间类型'">
                        <el-option :label="'用车时间'" :value="'0'"></el-option>
                        <el-option :label="'下单时间'" :value="'1'"></el-option>
                        <el-option :label="'续团时间'" :value="'2'"></el-option>
                    </el-select>

                    <el-date-picker :default-time="defaultTime" style="margin-left: 10px;width: 340px;"
                        v-model="timeTypeTime2" @change="timeTypeTime_btn2" type="datetimerange"
                        start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" />

                    <el-select v-model="find_data.orderByCondition" :placeholder="'排序'"
                        style="width: 80px;margin-left: 10px;">
                        <el-option :label="'升序'" :value="'0'"></el-option>
                        <el-option :label="'降序'" :value="'1'"></el-option>
                    </el-select>

                    <el-input style="width: 140px;margin-left: 10px;" placeholder="订单号" v-model="find_data.orderNum">
                    </el-input>

                    <el-input style="width: 220px;margin-left: 10px;" placeholder="行程详情/客户/驾驶员/业务员备注"
                        v-model="find_data.details">
                    </el-input>
                    <el-select v-model="find_data.statusList" multiple collapse-tags :placeholder="'订单状态'"
                        style="width: 180px;margin-left: 10px;">
                        <el-option v-for="it in orderStates" :label="it.name" :key="it.id" :value="it.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="find_data.payStatusList" multiple collapse-tags :placeholder="'付款状态'"
                        style="width: 140px;margin-left: 10px;">
                        <el-option v-for="it in payStatus_List" :label="it.name" :key="it.id" :value="it.id">
                        </el-option>
                    </el-select>
                    <div style="margin-top:10px;display: flex;">
                        <el-input style="width: 80px;" placeholder="座位数" maxlength="2"
                            onkeyup="this.value = this.value.replace(/^(0+)|[^\d]+/g, '');"
                            v-model="find_data.needSeats">
                        </el-input>
                        <el-input style="width: 100px;margin-left: 10px;" placeholder="车牌号" maxlength="8"
                            v-model="find_data.plateNum">
                        </el-input>
                        <el-input style="width: 180px;margin-left: 10px;" placeholder="驾驶员姓名/手机号" maxlength="11"
                            v-model="find_data.driverName">
                        </el-input>
                        <el-select @change="cusCompanySimpleName_change" clearable
                            style="width: 200px;margin-left: 10px;" filterable remote
                            :filter-method="findComboCusList_list_handleFilter" v-model="find_data.userId"
                            placeholder="请选择用车单位">
                            <el-option v-for="(item, index) in findComboCusList_list_yongche" :key="index"
                                :label="item.cusCompanyName" :value="item.userId">
                                <span style="float: left">{{ item.cusCompanyName }}</span>
                                <span style="
                        float: right;
                        color: var(--el-text-color-secondary);
                        font-size: 13px;
                      ">{{ item.cusRealName + '【' + item.cusPhone + '】' }}</span>
                            </el-option>
                        </el-select>
                        <el-select clearable v-model="find_data.useCarDutyUserId" :placeholder="'用车单位负责人'"
                            style="width: 140px;margin-left: 10px;">
                            <el-option v-for="it in dutyService_list" :label="it.name" :key="it.id" :value="it.id">
                            </el-option>
                        </el-select>

                        <el-select filterable remote :filter-method="handleFilter" @change="carCompanyId_change2"
                            clearable style="width: 200px;margin-left: 10px;" v-model="find_data.carCompanyId"
                            placeholder="请选择供车单位">
                            <el-option v-for="(item, index) in findComboCusList_list" :key="index"
                                :label="item.cusCompanyName" :value="item.id">
                                <span style="float: left">{{ item.cusCompanyName }}</span>
                                <span style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  ">{{ item.cusRealName + '【' + item.cusPhone + '】' }}</span>
                            </el-option>
                        </el-select>
                        <el-select clearable v-model="find_data.carDutyUserId" :placeholder="'供车负责人'"
                            style="width: 140px;margin-left: 10px;">
                            <el-option v-for="it in dutyService_list2" :label="it.name" :key="it.id" :value="it.id">
                            </el-option>
                        </el-select>
                        <el-input style="width: 150px;margin-left: 10px;" placeholder="操作编号"
                            v-model="find_data.operMark" clearable>
                        </el-input>
                        <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                            icon="Search">搜索</el-button>
                    </div>


                </div>


                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">付外调款</el-button>
                    <el-button @click="up_btn" type="primary" icon="WarnTriangleFilled">撤销付款</el-button>
                    <el-button @click="ex_getWalletListForBack_btn" type="primary" icon="Share">导出</el-button>
                </div>
                <div style="display:flex;height:30px;margin-top:5px;align-items: center;background:pink">
                    <b style="color:red;font-weight:700">收款总价:{{ totalPrice }}元</b>
                    <el-divider direction="vertical"></el-divider>
                    <b style="color:green;font-weight:700">外调总价:{{ totalOutPrice }}元</b>
                    <el-divider direction="vertical"></el-divider>
                    <b style="color:red;font-weight:700">已付款:{{ totalAlPayPrice }}元</b>
                    <el-divider direction="vertical"></el-divider>
                    <b style="color:green;font-weight:700">未付款:{{ totalPaySubPrice }}元</b>
                    <!-- <b>旅网总价:{{ gettravelPrepayPrice || 0.0 }}</b>
                    <el-divider direction="vertical"></el-divider>
                    <b>自网总价:{{ getselfPrepayPrice || 0.0 }}</b> -->
                </div>
            </template>
            <div>
                <el-table border @header-dragend='headerdragend' @selection-change="selection_change_btn" height="58vh"
                    ref="multipleTableRef" :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">

                            <template v-if="item.field == 'useCarCompanyId'" #="{ row, column, $index }">

                                <span>{{ useCarCompanyId_data_api(row) }}</span>
                            </template>
                            <template v-if="item.field == 'payStatus'" #="{ row, column, $index }">
                                {{ getServiceType(row.payStatus) }}
                            </template>
                            <template v-if="item.field == 'price'" #="{ row, column, $index }">
                                <span>{{ price_api(row) }}</span>
                            </template>
                            <template v-if="item.field == 'outPricealPayPrice'" #="{ row, column, $index }">

                                <span>{{ row.outPrice - row.alPayPrice }}</span>
                            </template>
                            <template v-if="item.field == 'useCarDutyInfo'" #="{ row, column, $index }">
                                <span>{{ useCarDutyInfo_data_api(row) }}</span>
                            </template>
                            <template v-if="item.field == 'carDutyUserInfo'" #="{ row, column, $index }">
                                <span>{{
                                    row.carDutyUserInfo ? row.carDutyUserInfo.split('-').length > 2 ?
                                        row.carDutyUserInfo.split('-')[1] + '-' + row.carDutyUserInfo.split('-')[2] :
                                        row.carDutyUserInfo.split('-')[0] + '-' + row.carDutyUserInfo.split('-')[1]
                                        : '' }}</span>
                            </template>

                            <template v-if="item.field == 'payStatus'" #="{ row, column, $index }">
                                {{ row.payStatus == 'UNPAID' ? '未付款' : row.payStatus == 'DEPOSIT_PAID' ? '已付定金' :
                                    row.payStatus == 'FULL_PAID' ? '全款已付' : row.payStatus == 'APPLY_SUCCESS' ? '申请成功' : '其他'
                                }}
                            </template>
                            <template v-if="item.field == 'driverName'" #="{ row, column, $index }">
                                <span>{{ row.driverName ? row.driverName + '-' + row.driverPhone : '' }}</span>
                            </template>
                            <template v-if="item.field == 'startDate'" #="{ row, column, $index }">
                                <span>{{ row.startTime.split(' ')[0] }}</span>
                            </template>
                            <template v-if="item.field == 'persons'" #="{ row, column, $index }">
                                <span>{{ row.serviceMan ? row.serviceMan.split('-')[1] + '-' +
                                    row.serviceMan.split('-')[2]
                                    : '' }}</span>
                            </template>
                            <template v-if="item.field == 'startTime'" #="{ row, column, $index }">
                                <span>{{ row.startTime.split(' ')[1] }}</span>
                            </template>
                            <template v-if="item.field == 'operNote'" #="{ row, column, $index }">

                                <el-tooltip :popper-class="'route-tips'" placement="left">
                                    <template #content>{{ row.operNote }}</template>
                                    <span style="  width: 100px; white-space: nowrap; text-overflow: ellipsis; ">{{
                                        row.operNote }}</span>
                                </el-tooltip>

                            </template>
                            <template v-if="item.field == 'endDate'" #="{ row, column, $index }">
                                <span>{{ row.endTime.split(' ')[0] }}</span>
                            </template>

                            <template v-if="item.field == 'endTime'" #="{ row, column, $index }">
                                <span>{{ row.endTime.split(' ')[1] }}</span>
                            </template>
                            <template v-if="item.field == 'details'" #="{ row, column, $index }">
                                <span>
                                    <span v-if='row.returnId' style='color:red'>【去程】</span>
                                    <span v-if='row.orderId' style='color:red'>【返程】</span>

                                    {{
                                        row.details }}</span>
                            </template>
                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[100, 200, 300, 500]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="50%" :close-on-click-modal='false'>
            <el-form :inline="true" :model="add_data" ref="formRef" label-width="130px" label-suffix="：">
                <div v-for="(item, index) in add_data">
                    <el-divider content-position="center">{{ item.details }}</el-divider>
                    <el-form-item label="付款金额">
                        <el-input style="width: 220px" v-model="add_data[index].payMoney" placeholder="付款金额"
                            clearable />
                    </el-form-item>

                </div>
                <el-divider content-position="center"></el-divider>
                <el-form-item label="摘要">
                    <el-input style="width: 520px" autosize show-word-limit maxlength="200" :rows="2" type="textarea"
                        placeholder="摘要" v-model="add_data_remark" />
                </el-form-item>
            </el-form>


            <el-button @click="ok_btn" style="margin-left:40vw" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import * as XLSX from 'xlsx';
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, payOrderProcessList, getServiceMans, servicePay, cancelServicePay, findComboCusList


} from '@/api/original_order_list.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    let payment_operation = JSON.parse(localStorage.getItem('payment_operation'))
    // if (payment_operation) {
    //     find_data.find = payment_operation.find
    // }
    getServiceMans({}).then(res => {
        serviceManList.value = res.data
    })
    getPrivateSetList({
        find: '付外调款',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);
        }
    })

    getServiceMans({

    }).then(res => {
        if (res.code == 1) {
            getServiceMans_list.value = res.data;

        }
    })
    findComboCusList({
        page: {
            pageNum: 1,
            pageSize: 999,
        },

        cusTypeMark: 'CARTEAM',

    }).then(res => {
        findComboCusList_list.value = res.data
    })
    findComboCusList({
        page: {
            pageNum: 1,
            pageSize: 999,
        },



    }).then(res => {
        findComboCusList_list_yongche.value = res.data
        findComboCusList_list_yongche2.value = res.data
    })
    timeTypeTime2.value = [new_day(), to_day()]
    find_data.stime = new_day()
    find_data.etime = to_day()



    await list_api()

})

//#region 表格数据处理
const serviceManList = ref([])
const getServericTypeText = (state) => {
    let result = serState.find((item) => item.id === state);
    return result.name || "--";
}
const getLockText = (data) => {
    let state = {
        UNLOCK: "未锁定",
        LOCKED: "已锁定",
    };
    return state[data] || "--";
}
const getServiceType = (val) => {
    let data = ''
    if (val == 'UNPAID') {
        data = '未付款'
    } else if (val == 'APPLY_SUCCESS') {
        data = '申请成功'
    } else if (val == 'DEPOSIT_PAID') {
        data = '已经付定金'
    } else if (val == 'FULL_PAID') {
        data = '全款已付'
    } else {
        data = '其他'
    }
    return data
}
const price_api = (e) => {
    let data = ''
    if (e.grabPrice > 0) {
        data = e.grabPrice
    } else {
        data = e.price
    }
    return data
}
const table_data_list = reactive([

    { label: "订单编号", field: "orderNum", width: 120, off: true },
    // { label: "订单编号", field: "payStatus", width: 120, off: true },

    { label: "付款状态", field: "payStatus", width: 120, off: true },
    { label: '驾驶员（电话）', field: 'driverName', width: 180, off: true },
    { label: "车牌号", field: "plateNum", width: 120, off: true },
    { label: '出发日期', field: 'startDate', width: 120, off: true },
    { label: '出发时间', field: 'startTime', width: 100, off: true },
    { label: '到达日期', field: 'endDate', width: 120, off: true },
    { label: '到达时间', field: 'endTime', width: 100, off: true },
    { label: '业务员', field: 'persons', width: 160, off: true },
    { label: '用车单位', field: 'useCarCompanyId', width: 220, off: true },
    { label: '用车负责人', field: 'useCarDutyInfo', width: 220, off: true },
    { label: '供车单位', field: 'carCompanyName', width: 220, off: true },
    { label: '供车负责人', field: 'carDutyUserInfo', width: 220, off: true },
    { label: "客人", field: "cusInfo", width: 220, off: true },
    { label: '客人备注', field: 'remark', width: 600, off: true },
    { label: '行程详情', field: 'details', width: 600, off: true },
    { label: "收款价格", field: "price", width: 100, off: true },
    { label: "已收金额(元)", field: "alGathPrice", width: 120, off: true },
    { label: "付款价格", field: "outPrice", width: 100, off: true },
    { label: "已付金额(元)", field: "alPayPrice", width: 120, off: true },
    { label: "应付余额(元)", field: "outPricealPayPrice", width: 120, off: true },
    { label: "操作编号", field: "operMark", width: 150, off: true },
    { label: "操作备注", field: "operNote", width: 150, off: true },


])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '付外调款',
        tbNum: "payment_operation",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion



//#region 分页列表
// 行程简称
const routeSimpleName_list = reactive([
    {
        value: '送天府',
        label: '送天府',
    },
    {
        value: '接天府',
        label: '接天府',
    },
    {
        value: '拼车送天府',
        label: '拼车送天府',
    },
    {
        value: '拼车接天府',
        label: '拼车接天府',
    },
    {
        value: '送双流',
        label: '送双流',
    },
    {
        value: '接双流',
        label: '接双流',
    },
    {
        value: '送东站',
        label: '送东站',
    },
    {
        value: '接东站',
        label: '接东站',
    },
    {
        value: '送西站',
        label: '送西站',
    },
    {
        value: '接西站',
        label: '接西站',
    },
    {
        value: '送南站',
        label: '送南站',
    },
    {
        value: '接南站',
        label: '接南站',
    }, {
        value: '送集合点大巴',
        label: '送集合点大巴',
    },
    {
        value: '接集合点大巴',
        label: '接集合点大巴',
    },
])
// 合并标识
const isMerge_list = reactive([
    {
        value: 'true',
        label: '合并',
    },
    {
        value: 'false',
        label: '未合并',
    },
])


const findComboCusList_list_yongche = ref([])
const findComboCusList_list_yongche2 = ref([])
const dutyService_list = ref([])
const findComboCusList_list_handleFilter = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = findComboCusList_list_yongche2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            findComboCusList_list_yongche.value = results
        } else {
            findComboCusList_list_yongche.value = []
        }
    } else {
        findComboCusList_list_yongche.value = findComboCusList_list_yongche2.value
    }
}
const cusCompanySimpleName_change = (e) => {
    for (let i = 0; i < findComboCusList_list_yongche2.value.length; i++) {
        if (e == findComboCusList_list_yongche2.value[i].userId) {
            let data = findComboCusList_list_yongche2.value[i].dutyService.split(',')
            dutyService_list.value = []
            console.log(data)

            for (let j = 0; j < data.length; j++) {
                let obj = {}
                obj.id = data[j].split('-')[0]
                obj.name = data[j].split('-')[1]
                obj.phone = data[j].split('-')[2]
                dutyService_list.value.push(obj)
            }
        }
    }
}
const findComboCusList_list = ref([])
const dutyService_list2 = ref([])

const carCompanyId_change2 = (e) => {
    console.log(e)
    for (let i = 0; i < findComboCusList_list.value.length; i++) {
        if (e == findComboCusList_list.value[i].id) {
            let data = findComboCusList_list.value[i].dutyService.split(',')
            dutyService_list2.value = []
            console.log(data)

            for (let j = 0; j < data.length; j++) {
                let obj = {}
                obj.id = data[j].split('-')[0]
                obj.name = data[j].split('-')[1]
                obj.phone = data[j].split('-')[2]
                dutyService_list2.value.push(obj)
            }
        }
    }
}
const orderStates = ref([
    { id: "READY_CAR", name: "未派车" },
    { id: "CAR_READY_CONFIRME", name: "未通知" },
    { id: "DRIVER_READY_RECEIVE", name: "已通知" },
    { id: "DRIVER_CONFIRMED", name: "师傅已确认" },
    { id: "ON_ROADING", name: "已出行" },
    { id: "FINIESHED", name: "已完成" },
    // { id: "CANCELED", name: "已取消" },
    // { id: "REFUSED", name: "已拒绝" },
    { id: "START_TAKE_CUS", name: "出发去接客户" },
    // { id: "DELETE", name: "已删除" },
    //     { id: "PENDING", name: "已待定" },
    //     { id: "GRAB_SUCCESS", name: "抢单成功" },
    //     { id: "TRANS_SUCCESS", name: "转接成功" },

])
const payStatus_List = ref([
    { id: "UNPAID", name: "未付款" },
    { id: "APPLY_SUCCESS", name: "申请成功(业务付款使用)" },
    { id: "DEPOSIT_PAID", name: "已付定金" },
    { id: "FULL_PAID", name: "全款已付" },

])

const useCarCompanyId_data_api = (e) => {
    let data = ''
    if (e.isCompanyCustomer == 1) {
        if (e.virtuallyUseCarInfo) {
            let data2 = ''
            if (e.useCarCompanyName) {
                data2 = e.useCarCompanyName ? e.useCarCompanyName : '匿名'
            } else {
                data2 = e.realName ? e.realName : '匿名'
            }
            data = e.virtuallyUseCarInfo.split('-')[0] + '【' + data2 + '】'
        } else {

            if (e.useCarCompanyName) {
                data = e.useCarCompanyName ? e.useCarCompanyName : '匿名'
            } else {
                data = e.realName ? e.realName : '匿名'
            }

        }
    } else if (e.isCompanyCustomer == 0 && e.companyNum == '8112010001') {
        if (e.virtuallyUseCarInfo) {
            let data2 = ''
            if (e.useCarCompanyName) {
                data2 = e.useCarCompanyName ? e.useCarCompanyName : '匿名'
            } else {
                data2 = e.realName ? e.realName : '匿名'
            }
            data = e.virtuallyUseCarInfo.split('-')[0] + '【' + data2 + '】'
        } else {

            if (e.useCarCompanyName) {
                data = e.useCarCompanyName ? e.useCarCompanyName : '匿名'
            } else {
                data = e.realName ? e.realName : '匿名'
            }

        }
    } else if (e.isCompanyCustomer == 0 && e.companyNum != '8112010001') {
        if (e.virtuallyUseCarInfo) {
            data = e.virtuallyUseCarInfo.split('-')[0] ? e.virtuallyUseCarInfo : '匿名'
        } else {
            data = '匿名'
        }

    }


    return data
}
const useCarDutyInfo_data_api = (e) => {
    let data = ''
    if (e.isCompanyCustomer == 1) {

        if (e.virtuallyUseCarInfo) {
            let realName = e.realName ? e.realName : '匿名'
            let mobile = e.mobile ? e.mobile : ''
            data = e.virtuallyUseCarInfo.split('-')[0] + '(' + e.useCarDutyInfo + ')'
        } else {
            let realName = e.realName ? e.realName : '匿名'
            let mobile = e.mobile ? e.mobile : ''
            data = e.useCarDutyInfo
        }

    } else if (e.isCompanyCustomer == 0 && e.companyNum == '8112010001') {

        if (e.virtuallyUseCarInfo) {
            let realName = e.realName ? e.realName : '匿名'
            let mobile = e.mobile ? e.mobile : ''
            data = e.virtuallyUseCarInfo.split('-')[0] + '(' + e.useCarDutyInfo + ')'
        } else {
            let realName = e.realName ? e.realName : '匿名'
            let mobile = e.mobile ? e.mobile : ''
            data = e.useCarDutyInfo
        }
    } else if (e.isCompanyCustomer == 0 && e.companyNum != '8112010001') {
        data = e.virtuallyUseCarInfo ? e.virtuallyUseCarInfo.split('-')[0] : '匿名'
    }


    return data


}

const getServiceMans_list = ref([])
const list_data = ref([])
const new_day = () => {
    // 获取当前日期
    let currentDate = new Date();

    // 计算上个月的年份和月份
    let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
    let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

    // 构建上个月的日期
    let firstDayOfLastMonth = new Date(year, month, 1);

    // 格式化为 yyyy-mm-dd
    let formattedDate = `${firstDayOfLastMonth.getFullYear()}-${(firstDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-01`;

    let formattedDate2 = `${formattedDate} 00:00:00`;
    return formattedDate2
}
const to_day = () => {
    // 获取当前日期
    let currentDate = new Date();

    // 计算上个月的年份和月份
    let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
    let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

    // 获取上个月的最后一天
    let lastDayOfLastMonth = new Date(year, month + 1, 0);

    // 格式化为 yyyy-mm-dd
    let formattedDate = `${lastDayOfLastMonth.getFullYear()}-${(lastDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-${lastDayOfLastMonth.getDate()}`;

    let formattedDate2 = `${formattedDate} 23:59:59`;
    return formattedDate2
}
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const timeTypeTime2 = ref([])
const timeTypeTime_btn2 = (e) => {
    if (e) {
        timeTypeTime2.value = e
        find_data.stime = timeTypeTime2.value[0]
        find_data.etime = timeTypeTime2.value[1]
    } else {
        timeTypeTime2.value = ''
        find_data.stime = ''
        find_data.etime = ''
        find_data.timeType = ''
    }
}
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 100,
    },
    routeSimpleName: '',
    serviceMan: '',
    timeType: '0',
    stime: '',
    etime: '',
    orderByCondition: '0',
    orderNum: '',
    details: '',
    statusList: [],
    needSeats: '',
    plateNum: '',
    driverName: '',
    userId: '',
    useCarDutyUserId: '',
    carCompanyId: '',
    carDutyUserId: '',
    payStatusList: [],
    operMark: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}
const totalAlPayPrice = ref(0)
const totalOutPrice = ref(0)
const totalPaySubPrice = ref(0)
const totalPrice = ref(0)
const list_api = () => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在加载，中请稍后...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let serviceMan_data = find_data.serviceMan
    if (find_data.serviceMan) {
        for (let i = 0; i < getServiceMans_list.value.length; i++) {
            if (find_data.serviceMan == getServiceMans_list.value[i].ftUserId) {
                find_data.serviceMan = getServiceMans_list.value[i].ftUserId + '-' + getServiceMans_list.value[i].realName + '-' + getServiceMans_list.value[i].loginPhone
            }
        }

    }
    payOrderProcessList(find_data).then(res => {
        loading.close()
        find_data.serviceMan = serviceMan_data
        // 应付余额=派单总价-已付金额
        list_data.value = res.data.list.list.map((item) => {
            item.dealPrice = parseFloat(item.disPrice) - parseFloat(item.alPayPrice);
            return item;
        });
        total.value = res.data.list.total
        totalAlPayPrice.value = res.data.totalAlPayPrice
        totalOutPrice.value = res.data.totalOutPrice
        totalPaySubPrice.value = res.data.totalPaySubPrice
        totalPrice.value = res.data.totalPrice
        list_page.value.pageSize = res.data.list.total
    })
}
//#endregion

//#region 添加
const add_off = ref(false)
const title = ref('申请付款')
const add_data = ref([])
const add_data_remark = ref('')
const add_btn = () => {
    if (table_list.value.length < 1) {
        return ElMessage({
            message: '请选择至少一条数据！',
            type: 'warning',
        })
    }
    title.value = '申请付款'
    add_data.value = []
    let list = []
    for (let i = 0; i < table_list.value.length; i++) {
        let data = {
            details: table_list.value[i].details,
            orderId: table_list.value[i].id,
            payMoney: table_list.value[i].outPrice - table_list.value[i].alPayPrice,
            remark: "",
        }
        list.push(data)
    }
    add_data_remark.value = ''
    add_data.value = list




    add_off.value = true

}
const ok_btn = () => {
    ElMessageBox.confirm(
        '确认申请付款?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            let ps = {
                ids: [],
                outPrice: '0',
                remark: '',
            }
            for (let i = 0; i < add_data.value.length; i++) {
                ps.ids.push(add_data.value[i].orderId)
                ps.outPrice = Number(ps.outPrice) + Number(add_data.value[i].payMoney)
            }
            ps.remark = add_data_remark.value
            servicePay(ps).then(res => {
                if (res.code == 1) {
                    list_api()
                    add_off.value = false
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    add_off.value = false
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })


        })
        .catch((e) => {


        })


}

//#endregion

//#region 表格选择
const table_list = ref([])
const headerdragend = (newWidth, oldWidth, column) => {
    console.log(newWidth, oldWidth, column)
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (column.property == table_data_list_new.value[i].field) {
            table_data_list_new.value[i].width = newWidth
        }
    }
}
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    if (table_list.value[0].payStatus != 'APPLY_SUCCESS') {
        return ElMessage({
            message: '请选择【申请成功】的订单进行撤销',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认撤销付款申请?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            cancelServicePay({
                ids: [table_list.value[0].id]
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })
}
//#endregion




//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认删除【${table_list.value[0].bankName}】账户?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delBank({
                id: table_list.value[0].id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
   
    list_api()
}
//#endregion

//#region 导出
const list_page = ref({
    pageNum: 1,
    pageSize: 100,
})
const ex_getWalletListForBack_btn = () => {
    let ps = {
        page: list_page.value,
        routeSimpleName: find_data.routeSimpleName,
        serviceMan: find_data.serviceMan,
        timeType: find_data.timeType,
        stime: find_data.stime,
        etime: find_data.etime,
        orderByCondition: find_data.orderByCondition,
        orderNum: find_data.orderNum,
        details: find_data.details,
        statusList: find_data.statusList,
        needSeats: find_data.needSeats,
        plateNum: find_data.plateNum,
        driverName: find_data.driverName,
        userId: find_data.userId,
        useCarDutyUserId: find_data.useCarDutyUserId,
        carCompanyId: find_data.carCompanyId,
        carDutyUserId: find_data.carDutyUserId,
        payStatusList: find_data.payStatusList,
    }


    payOrderProcessList(ps).then(res => {
        if (res.code == 1) {

            const data = [
                ['订单编号', '付款状态', '驾驶员（电话）', '车牌号', '出发日期', '出发时间', '到达日期', '到达时间', '业务员', '用车单位', '用车负责人', '供车单位', '供车负责人',  '客户备注', '行程详情', '收款价格', '已收金额(元)', '付款价格', '已付金额(元)', '应付余额(元)',],
            ];
            for (let i = 0; i < res.data.list.list.length; i++) {
                let ps = {
                    orderNum: res.data.list.list[i].orderNum,
                    payStatus: getServiceType(res.data.list.list[i].payStatus),
                    driverName: res.data.list.list[i].driverName + '-' + res.data.list.list[i].driverPhone,
                    plateNum: res.data.list.list[i].plateNum,
                    startDate: res.data.list.list[i].startTime.split(' ')[0],
                    startTime: res.data.list.list[i].startTime.split(' ')[1],
                    endDate: res.data.list.list[i].endTime.split(' ')[0],
                    endTime: res.data.list.list[i].endTime.split(' ')[1],
                    persons: res.data.list.list[i].serviceMan ? res.data.list.list[i].serviceMan.split('-')[1] + '-' + res.data.list.list[i].serviceMan.split('-')[2] : '',
                    useCarCompanyId: useCarCompanyId_data_api(res.data.list.list[i]),
                    useCarDutyInfo: useCarDutyInfo_data_api(res.data.list.list[i]),
                    carCompanyName: res.data.list.list[i].carCompanyName,
                    carDutyUserInfo: res.data.list.list[i].carDutyUserInfo ? res.data.list.list[i].carDutyUserInfo.split('-').length > 2 ?
                        res.data.list.list[i].carDutyUserInfo.split('-')[1] + '-' + res.data.list.list[i].carDutyUserInfo.split('-')[2] :
                        res.data.list.list[i].carDutyUserInfo.split('-')[0] + '-' + res.data.list.list[i].carDutyUserInfo.split('-')[1]
                        : '',
                    // cusName: res.data.list.list[i].cusName,
                    remark: res.data.list.list[i].remark,
                    details: res.data.list.list[i].details,
                    price: price_api(res.data.list.list[i]),
                    alGathPrice: res.data.list.list[i].alGathPrice,
                    outPrice: res.data.list.list[i].outPrice,
                    alPayPrice: res.data.list.list[i].alPayPrice,
                    outPricealPayPrice: res.data.list.list[i].outPrice - res.data.list.list[i].alPayPrice,



                }
                data.push(Object.values(ps))
            }

            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '单位管理后台系统-付外调款.xlsx');

            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion

</script>

<style scoped lang='scss'>
.route-tips {
    max-width: 500px !important;
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
